package com.sitech.webapp.filter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sitech.BaseConst;
import com.sitech.domain.LoginUser;

public class LoginFilter implements Filter
{
	private static String filter_urls;
	private static String non_filter_urls;
	private static String exclue_Paramete = "exclude";
	private Pattern pattern = null;

	public void destroy()
	{

	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException
	{
		HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
		HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

		if (!checkUlr(httpRequest.getServletPath()))
		{
			LoginUser user = (LoginUser) httpRequest.getSession().getAttribute(BaseConst.SESSION_USER_KEY);

			if (user == null)
			{
				System.out.println("getContextPath: " + httpRequest.getContextPath());
				httpResponse.sendRedirect(httpRequest.getContextPath());
				return;
			}
			// 添加逻辑判断是否是admin，则不用校验
			if (user.getUserName().equals("admin"))
			{
				httpResponse.setContentType("text/html;charset=utf-8");
				httpResponse.setCharacterEncoding("utf-8");
				chain.doFilter(httpRequest, httpResponse);
				return;
			}

			// 帐号状态判断：state，0正常，1锁定，2注销，其它未知
			// 如果帐号状态为1锁定、2注销、其它非0状态，则不允许登陆系统
			int state = user.getState();
			if (state != 0)
			{
				httpResponse.sendRedirect(httpRequest.getContextPath() + "/login/refuseLogin.action");
				return;
			}
			int passwdStatus = user.getPwd_status().intValue();
			// 密码状态判断：pwd_status，0正常，1重置，2失效，其它未知
			// 密码状态为2失效时，则不允许登陆系统，如果为重置时则在登陆后修改密码，此逻辑在forceUpdatePwd.action实现
			if (passwdStatus == 2)
			{
				httpResponse.sendRedirect(httpRequest.getContextPath() + "/login/refuseLogin.action");
				return;
			}
		}
		httpResponse.setContentType("text/html;charset=utf-8");
		httpResponse.setCharacterEncoding("utf-8");
		chain.doFilter(httpRequest, httpResponse);
	}

	public void init(FilterConfig filterConfig) throws ServletException
	{
		non_filter_urls = filterConfig.getInitParameter(exclue_Paramete);
		pattern = Pattern.compile(non_filter_urls);
	}

	private boolean checkUlr(String requestPath)
	{
		Matcher matcher = pattern.matcher(requestPath);
		return matcher.find();
	}

}
